//
//  PlistLoader.swift
//  Mall-swift
//
//  Created by dfpo on 2020/10/25.
//  Copyright © 2020 Bob. All rights reserved.
//

import Foundation

final class PlistLoader {
    private static var bundleName: String = "basePod"+".bundle"
    
    /// 加载plist文件，如  let dict = PlistLoader.loadPlist(name: "AppEnvironment") as? [String: [String:[String:String]]]
    static func loadPlist(name: String) -> [String: Any]? {
        
        guard let path = Bundle(for: self).path(forResource: name, ofType: "plist", inDirectory: bundleName) else {
            return nil
        }
        
        
        return NSDictionary(contentsOfFile: path) as? [String: Any]
    }
    
    /// 从main bundle中加载Plist为某种类型的数据
    /// - Parameter name: plist名，不带.plist
    /// - Returns: 返回类型，需要自己指定， 例如 let dict: [String: [String:[String:String]]] = loadPlist(name: "AppEnvironment")
    static func loadPlist<T>(name: String) -> T? {
        guard  let path = Bundle(for: self).path(forResource: name, ofType: "plist", inDirectory: bundleName),
               let data = try? Data(contentsOf: URL(fileURLWithPath: path)),
               let dict = try? PropertyListSerialization.propertyList(from: data, options: .mutableContainers, format: nil) as? T else {
            return nil
        }
        return dict
    }
}
